package cn.com.twoke.app.pin_dou_dou.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 图像像素化工具类
 */
public class ImagePixelUtils {

    // 步长为5比较像像素风格
    // 对于较大的图像，可能需要更大的值
    private static final int STEP = 5;

    /**
     * 将图像转换为像素风格
     * @param imagePath 本地图像文件路径
     * @return 像素风格的BufferedImage
     * @throws Exception 图像处理过程中发生错误时抛出
     */
    public static BufferedImage getPixelImage(String imagePath) throws Exception {
        return getPixelImage(imagePath, STEP);
    }
    
    /**
     * 使用自定义步长将图像转换为像素风格
     * @param imagePath 本地图像文件路径
     * @param customStep 自定义步长
     * @return 像素风格的BufferedImage
     * @throws Exception 图像处理过程中发生错误时抛出
     */
    public static BufferedImage getPixelImage(String imagePath, int customStep) throws Exception {
        BufferedImage bi = ImageIO.read(new File(imagePath));
        int width = bi.getWidth();
        int height = bi.getHeight();
        int minX = bi.getMinX();
        int minY = bi.getMinY();
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = img.createGraphics();
        for (int i = minX; i < width; i = i + customStep) {
            for (int j = minY; j < height; j = j + customStep) {
                int pixelRGB = bi.getRGB(i, j);
                int red = (pixelRGB >> 16) & 0xff;
                int green = (pixelRGB >> 8) & 0xff;
                int blue = (pixelRGB) & 0xff;
                graphics.setColor(new Color(red, green, blue)); // 设置画笔颜色
                //graphics.fillRect(i,j,k,k); // 填充矩形
                graphics.fillRoundRect(i, j, customStep, customStep, -1, -1); // 填充圆角矩形
            }
        }
        return img;
    }
}